import { Context } from 'koa';
import { AppContext } from '@/types';
import AuthService from '@/services/AuthService';
import { validate, commonSchemas } from '@/utils/validator';
import * as response from '@/utils/response';
import Joi from 'joi';

/**
 * 认证控制器
 */
export class AuthController {
  /**
   * 用户登录
   */
  async login(ctx: Context) {
    const appCtx = ctx as AppContext;

    const schema = Joi.object({
      email: commonSchemas.email.required(),
      password: Joi.string().required(),
      tenantId: Joi.string().optional(), // 允许手动指定租户ID
    });

    const data = await validate<{ email: string; password: string; tenantId?: string }>(ctx.request.body as any, schema);

    // 优先使用手动指定的 tenantId，其次使用子域名识别的 tenant
    const tenantId = data.tenantId || appCtx.state.tenant?.id;

    const result = await AuthService.login(
      data.email,
      data.password,
      tenantId,
      ctx.ip,
      ctx.get('user-agent'),
    );

    response.success(ctx, result, '登录成功');
  }

  /**
   * 获取可用租户列表（公开接口，用于登录页选择）
   */
  async getAvailableTenants(ctx: Context) {
    const Tenant = (await import('@/models/Tenant.model')).default;
    
    // 只返回激活状态的租户
    const tenants = await Tenant.findAll({
      where: {
        status: 'active',
      },
      attributes: ['id', 'name', 'subdomain'],
      order: [['name', 'ASC']],
    });

    response.success(ctx, tenants);
  }

  /**
   * 刷新 Token
   */
  async refreshToken(ctx: Context) {
    const appCtx = ctx as AppContext;

    if (!appCtx.state.user) {
      return response.unauthorized(ctx, '未授权');
    }

    const result = await AuthService.refreshToken(appCtx.state.user.id);

    response.success(ctx, result, 'Token 刷新成功');
  }

  /**
   * 用户登出
   */
  async logout(ctx: Context) {
    const appCtx = ctx as AppContext;

    if (!appCtx.state.user) {
      return response.unauthorized(ctx, '未授权');
    }

    await AuthService.logout(
      appCtx.state.user.id,
      ctx.ip,
      ctx.get('user-agent'),
    );

    response.success(ctx, null, '登出成功');
  }

  /**
   * 修改密码
   */
  async changePassword(ctx: Context) {
    const appCtx = ctx as AppContext;

    if (!appCtx.state.user) {
      return response.unauthorized(ctx, '未授权');
    }

    const schema = Joi.object({
      oldPassword: Joi.string().required(),
      newPassword: commonSchemas.password.required(),
    });

    const data = await validate<{ oldPassword: string; newPassword: string }>(ctx.request.body as any, schema);

    await AuthService.changePassword(
      appCtx.state.user.id,
      data.oldPassword,
      data.newPassword,
    );

    response.success(ctx, null, '密码修改成功');
  }

  /**
   * 获取当前用户信息
   */
  async getCurrentUser(ctx: Context) {
    const appCtx = ctx as AppContext;

    if (!appCtx.state.user) {
      return response.unauthorized(ctx, '未授权');
    }

    // 从数据库获取完整的用户信息
    const User = (await import('@/models/User.model')).default;
    const Role = (await import('@/models/Role.model')).default;
    
    const user = await User.findByPk(appCtx.state.user.id, {
      include: [
        {
          model: Role,
          as: 'role',
          attributes: ['id', 'name', 'description'],
        },
      ],
    });

    if (!user) {
      return response.unauthorized(ctx, '用户不存在');
    }

    response.success(ctx, user.toSafeObject());
  }

  /**
   * 获取当前用户权限列表
   */
  async getCurrentUserPermissions(ctx: Context) {
    const appCtx = ctx as AppContext;

    if (!appCtx.state.user) {
      return response.unauthorized(ctx, '未授权');
    }

    // 动态导入以避免循环依赖
    const { getUserPermissions } = await import('@/middlewares/permission');
    const permissions = await getUserPermissions(appCtx.state.user.id);

    response.success(ctx, {
      permissions,
      isSuperAdmin: appCtx.state.user.type === 'super_admin',
    });
  }

  /**
   * 更新当前用户信息
   */
  async updateCurrentUser(ctx: Context) {
    const appCtx = ctx as AppContext;

    if (!appCtx.state.user) {
      return response.unauthorized(ctx, '未授权');
    }

    const schema = Joi.object({
      firstName: Joi.string().allow('').max(100),
      lastName: Joi.string().allow('').max(100),
      avatar: Joi.string().uri().allow(''),
    });

    interface UpdateProfileData {
      firstName?: string;
      lastName?: string;
      avatar?: string;
    }

    const data = await validate<UpdateProfileData>(ctx.request.body as any, schema);

    const user = await AuthService.updateProfile(appCtx.state.user.id, data);

    response.success(ctx, user.toSafeObject(), '个人信息更新成功');
  }
}

export default new AuthController();

